package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommomResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * description: todo
 *
 * @author sun jun
 * @className PayMentController
 * @date 2020/3/18 15:24
 */
@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/create")
    public CommomResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);

        if (result > 0){
            return new CommomResult(200,"成功"+serverPort,result);
        }else {
            return new CommomResult(200,"失败"+serverPort,null);
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommomResult getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        System.out.println("热部署成功");
        if (payment != null){
            return new CommomResult(200,"成功"+serverPort,payment);
        }else {
            return new CommomResult(200,"失败"+serverPort,null);
        }
    }

    @GetMapping("/payment/discovery")
    public Object getDiscoveryClient(){
        List<String> servers = discoveryClient.getServices();
        for (String ele:servers) {
            log.info("server...{}",ele);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("instanceId...{}",instance.getInstanceId());
            log.info("host...{}",instance.getHost());
            log.info("uri...{}",instance.getUri());
        }

        return this.discoveryClient;

    }

}
